﻿using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using Telerik.Web.UI;
using MediaMonitor.Common;
using System.Collections;
using System.Net.Mail;
using System.Configuration;
using System.IO;

namespace MediaMonitor.Users
{
    public partial class NewCommercial_filter : Adex.BasePage
    {
        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        private string categoryCode = "";
        private string mediaCodes = "";

        private string sectorCode = "";

        private string subsector = "", advertiser = "";

        private static string AppName = ConfigurationManager.AppSettings["AppName"].ToString();
        private static string AdminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Company"] != null)
            {
                if (!IsPostBack)
                {
                    Utility.AddDateControlToPage(this.Page);

                    ddlBinds();
                    // SetCalendarDates();
                    //calS.SelectedDate = DateTime.Now.Date;
                    //calE.SelectedDate = DateTime.Now.Date;
                    // FillMedia(1);
                    FillMediaTypes();
                    //FillPrograms(1);

                    FillSectors();
                    FillSubSectors();
                    FillCategories();
                    FillAdvertisers();
                    //FillAgencies(1);
                    Session["TVCRUserWriteProductName"] = 0;
                    Session["TVCRVerUserWriteProductName"] = 0;

                    Session["TVCRUserWriteProductNameText"] = "";
                    Session["TVCRVerUserWriteProductNameText"] = "";
                    //hdnEmails.Value = emailsTO(1);
                    //hdnMediaCodeforEmails.Value = "1";
                }
            }
            else
            {
                Response.Redirect("../logout.aspx");
            }
        }
        protected void ddlBinds()
        {
            // Bind Duratios and Estimated DropDowns
            for (int i = 0; i <= 23; i++)
            {
                string time = i.ToString();
                time = (i.ToString().Length < 2) ? "0" + time : time;
                ListItem itmTime = new ListItem(time, time);
                ddlHours.Items.Add(itmTime);
                //ddlEstimatedHour.Items.Add(itmTime);
                ddlEstimatedhoursFirstAppearance.Items.Add(itmTime);
                ddlEstimatedhoursSecondAppearance.Items.Add(itmTime);
                ddlEstimatedhoursThirdAppearance.Items.Add(itmTime);
            }
            for (int i = 0; i <= 59; i++)
            {
                string time = i.ToString();
                time = (i.ToString().Length < 2) ? "0" + time : time;
                ListItem itmTime = new ListItem(time, time);
                ddlMinutes.Items.Add(itmTime);
                ddlSeconds.Items.Add(itmTime);
                //ddlEstimatedMinute.Items.Add(itmTime);
                ddlEstimatedMinutesFirstAppearance.Items.Add(itmTime);
                ddlEstimatedMinutesSecondAppearance.Items.Add(itmTime);
                ddlEstimatedMinutesThirdAppearance.Items.Add(itmTime);
            }

            ddlHours.SelectedIndex = 0;
            ddlMinutes.SelectedIndex = 0;
            ddlSeconds.SelectedIndex = 0;
            //ddlEstimatedHour.SelectedIndex = 0;
            //ddlEstimatedMinute.SelectedIndex = 0;
            ddlEstimatedMinutesFirstAppearance.SelectedIndex = 0;
            ddlEstimatedMinutesSecondAppearance.SelectedIndex = 0;
            ddlEstimatedMinutesThirdAppearance.SelectedIndex = 0;
            ddlEstimatedhoursFirstAppearance.SelectedIndex = 0;
            ddlEstimatedhoursSecondAppearance.SelectedIndex = 0;
            ddlEstimatedhoursThirdAppearance.SelectedIndex = 0;
            // Fill Agency Text box
            txtAgency.Text = Session["Company"].ToString();

        }
        private static DataSet GetLookupDataSet()
        {

            //if (HttpContext.Current.Cache["dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString()] == null)
            //{
            //Get Lookup Tables filtered by User / Company settings

            //DataSet ds = SPs.SpGetReportFilterLookupTables(AppUser.CurrUserID).GetDataSet();
            DataSet ds = SPs.GetLookupTables2(AppUser.CurrUserID, "TVCR").GetDataSet();
            ds.Tables[0].TableName = "MediaType";
            ds.Tables[1].TableName = "Media";

            ds.Tables[3].TableName = "Advertiser";
            ds.Tables[4].TableName = "Brand";
            ds.Tables[5].TableName = "Sector";
            ds.Tables[6].TableName = "SubSector";
            ds.Tables[7].TableName = "Category";
            ds.Tables[8].TableName = "Product";
            ds.Tables[9].TableName = "ProdVersion";

            //HttpContext.Current.Cache.Insert("dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);


            return ds;

            //}
            //else
            //{
            // return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString()]));
            //}
        }
        private static DataSet GetLookupDataSet2()
        {

            //if (HttpContext.Current.Cache["dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString()] == null)
            //{
            //Get Lookup Tables filtered by User / Company settings

            //DataSet ds = SPs.SpGetReportFilterLookupTables(AppUser.CurrUserID).GetDataSet();
            DataSet ds = SPs.GetLookupTables(AppUser.CurrUserID, "TVCR").GetDataSet();
            ds.Tables[0].TableName = "MediaType";
            ds.Tables[1].TableName = "Media";

            ds.Tables[3].TableName = "Advertiser";
            ds.Tables[4].TableName = "Brand";
            ds.Tables[5].TableName = "Sector";
            ds.Tables[6].TableName = "SubSector";
            ds.Tables[7].TableName = "Category";
            ds.Tables[8].TableName = "Product";
            ds.Tables[9].TableName = "ProdVersion";

            //HttpContext.Current.Cache.Insert("dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);


            return ds;

            //}
            //else
            //{
            // return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_TVCR_" + AppUser.CurrUserID.ToString()]));
            //}
        }
        #region FillLists


        private void FillSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[5];

            string filter = "1=1";
            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType = 'TVCR' AND  TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType = 'PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType = 'OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType = 'NS' AND NS = 1";
            //            break;
            //        }
            //}

            string sort = "SectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "SectorCode", "SectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SectorName");
                lstSector.Items.Clear();
                lstSector.DataSource = dtcolumns;
                lstSector.DataBind();
            }
            lstSector.Items.Insert(0, new ListItem("- ALL -", "0"));
        }


        public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
            //And add duplicate item value in arraylist.
            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            //Removing a list of duplicate items from datatable.
            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            //Datatable which contains unique records will be return as output.
            return dTable;
        }

        private void FillSubSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[6];

            string filter = "1=1";
            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType = 'TVCR'  AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType = 'PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType = 'OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType = 'NS' AND NS = 1";
            //            break;
            //        }
            //}

            filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";

            string sort = "SubSectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            DataTable dtcolumns = dv.ToTable(true, "SubSectorCode", "SubSectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SubSectorName");
                lstSubSector.Items.Clear();
                lstSubSector.DataSource = dtcolumns;
                lstSubSector.DataBind();
                lstSubSector2.Items.Clear();
                lstSubSector2.DataSource = dtcolumns;
                lstSubSector2.DataBind();
            }

            lstSubSector.Items.Insert(0, new ListItem("- ALL -", "0"));
            lstSubSector2.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        private void FillCategories()
        {
            DataTable dt = GetLookupDataSet().Tables[7];

            string filter = "1=1";




            //switch (lstMediaType.SelectedValue)
            //{
            //    case "1":
            //        {
            //            filter += " AND MediaType='TVCR' AND TV = 1";
            //            break;
            //        }

            //    case "3":
            //        {
            //            filter += " AND MediaType='TVCR' AND RD = 1";
            //            break;
            //        }
            //    case "5":
            //        {
            //            filter += " AND MediaType='TVCR' AND CB = 1";
            //            break;
            //        }
            //    case "6":
            //        {
            //            filter += " AND MediaType='PR' AND PR = 1";
            //            break;
            //        }
            //    case "7":
            //        {
            //            filter += " AND MediaType='OD' AND OD = 1";
            //            break;
            //        }
            //    case "8":
            //        {
            //            filter += " AND MediaType='NS' AND NS = 1";
            //            break;
            //        }
            //}

            // filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";
            filter += lstSubSector.SelectedValue != "0" ? " AND SubSectorCode=" + lstSubSector.SelectedValue : "";

            string sort = "CategoryName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            DataTable dtcolumns = dv.ToTable(true, "CategoryCode", "CategoryName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "CategoryName");
                lstCategory.Items.Clear();
                lstCategory.DataSource = dtcolumns;
                lstCategory.DataBind();
            }

            lstCategory.Items.Insert(0, new ListItem("- ALL -", "0"));
            lstCategory.Items.Insert(1, new ListItem("Not Found", "Not Found"));
            // lstCategory.Items.Insert(dtcolumns.Rows.Count+1,new ListItem("OTHER", "OTHER"));
        }

        private void FillAdvertisers()
        {
            DataTable dt = GetLookupDataSet().Tables[3];
            if (dt.Rows.Count > 0)
            {
                dt = RemoveDuplicateRows(dt, "AdvertiserName");
                lstAdvertiser.Items.Clear();
                lstAdvertiser.DataSource = dt;
                lstAdvertiser.DataBind();
            }


            lstAdvertiser.Items.Insert(0, new ListItem("- ALL -", ""));
        }

        //private void FillAgencies(int mediaTypeCode)
        //{
        //    DataTable dt = GetLookupDataSet(mediaTypeCode).Tables[1];

        //    string filter = "1=1";
        //    //switch (lstMediaType.SelectedValue)
        //    //{
        //    //    case "1":
        //    //        {
        //    //            filter += " AND MediaType='TVCR' AND TV = 1";
        //    //            break;
        //    //        }

        //    //    case "3":
        //    //        {
        //    //            filter += " AND MediaType='TVCR' AND RD = 1";
        //    //            break;
        //    //        }
        //    //    case "5":
        //    //        {
        //    //            filter += " AND MediaType='TVCR' AND CB = 1";
        //    //            break;
        //    //        }
        //    //    case "6":
        //    //        {
        //    //            filter += " AND MediaType='PR' AND PR = 1";
        //    //            break;
        //    //        }
        //    //    case "7":
        //    //        {
        //    //            filter += " AND MediaType='OD' AND OD = 1";
        //    //            break;
        //    //        }
        //    //    case "8":
        //    //        {
        //    //            filter += " AND MediaType='NS' AND NS = 1";
        //    //            break;
        //    //        }
        //    //}
        //    string sort = "AgencyName";

        //    DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
        //    DataTable dtcolumns = dv.ToTable(true, "AgencyCode", "AgencyName");


        //        dtcolumns = RemoveDuplicateRows(dtcolumns, "AgencyName");
        //        lstAgency.DataSource = dtcolumns;
        //        lstAgency.DataBind();


        //    lstAgency.Items.Insert(0, new ListItem("- ALL -", "0"));
        //}

        protected void lstSector_Changed(object sender, EventArgs e)
        {
            FillSubSectors();
            FillCategories();

        }

        protected void lstSubSector_Changed(object sender, EventArgs e)
        {
            FillCategories();


        }
        protected void lstCategory_Changed(object sender, EventArgs e)
        {
            if (lstCategory.SelectedValue.ToString().ToLower() == "not found")
            {
                txtCategory.Visible = true;
            }
            else
                txtCategory.Visible = false;
        }
        #endregion
        #region Fill Media
        private void FillMediaTypes()
        {

            lstMediaType.DataSource = GetLookupDataSet2().Tables["MediaType"];
            lstMediaType.DataBind();

            Utility.SelectListItemByText(lstMediaType, "TV");
            // lstMediaType.Items.Insert(0, new ListItem("- Select -", "Select"));
            // FillMedia(Utility.ToInt(lstMediaType.SelectedValue));

        }
        private void FillMedia(int MediaTypeCode)
        {


            if (MediaTypeCode > 0)
                lstMedia.DataSource = new DataView(GetLookupDataSet2().Tables["Media"], "MediaTypeCode=" + MediaTypeCode.ToString(), "MediaName", DataViewRowState.OriginalRows);
            else
                lstMedia.DataSource = GetLookupDataSet2().Tables["Media"];


            lstMedia.DataBind();


        }
        protected void lstMediaType_SelectedIndexChanged(object sender, EventArgs e)
        {


            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));
            pnlUpdate_Media.Update();

            //FillAdvertisers(Convert.ToInt32(lstMediaType.SelectedValue));
            //FillAgencies(Convert.ToInt32(lstMediaType.SelectedValue));
            //FillPrograms(Convert.ToInt32(lstMediaType.SelectedValue));

        }
        #endregion
        #region AutoComplete Functions


        [WebMethod]
        public static string[] AutoComplete_FillBrand(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[4];

            string filter = "1=1 ";
            string filterwrite = "1=1 ";

            filter += " AND MediaType='TVCR' AND BrandName LIKE '" + prefixText + "%'";

            filterwrite += " AND MediaType='TVCR' AND BrandName ='" + prefixText + "'";

            DataRow[] drsUserWrite = dt.Select(filterwrite);
            try
            {
                if (drsUserWrite.Length == 1) //If user write and that item is in database
                {
                    HttpContext.Current.Session["TVCRUserWriteProductName"] = drsUserWrite[0][0];
                    HttpContext.Current.Session["TVCRUserWriteProductNameText"] = drsUserWrite[0][2];

                }
                else
                {
                    HttpContext.Current.Session["TVCRUserWriteProductName"] = -1;
                    HttpContext.Current.Session["TVCRUserWriteProductNameText"] = "";
                }
            }
            catch { }

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["BrandName"].ToString(), dr["BrandID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillProduct(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            filter += " AND MediaType='TVCR' AND ProductName LIKE '" + prefixText + "%'";

            //get brand 

            if (contextKey != null && contextKey != "" && contextKey != "0")
            {
                filter += " AND BrandID = " + contextKey;
            }

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[8];

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProductName"].ToString(), dr["ProductID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillVersion(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            string filterwrite = "1=1 ";

            filter += " AND MediaType='TVCR' AND ProdVersionName LIKE '" + prefixText + "%'";
            filterwrite += " AND MediaType='TVCR' AND ProdVersionName ='" + prefixText + "'";
            //get brand 

            //if (contextKey != null && contextKey != "" && contextKey != "0")
            //{
            //}




            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[9];


            DataRow[] drsUserWrite = dt.Select(filterwrite);
            try
            {
                if (drsUserWrite.Length == 1) //If user write and that item is in database
                {
                    HttpContext.Current.Session["TVCRVerUserWriteProductName"] = drsUserWrite[0][0];
                    HttpContext.Current.Session["TVCRVerUserWriteProductNameText"] = drsUserWrite[0][2];
                }
                else
                {
                    HttpContext.Current.Session["TVCRVerUserWriteProductName"] = -1;
                    HttpContext.Current.Session["TVCRVerUserWriteProductNameText"] = "";
                }
            }
            catch { }


            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProdVersionName"].ToString(), dr["ProdVersionID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        #endregion
        private string GenerateId()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }
        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            if (lblFirstAppearance.Text == "" && lblSecondAppearance.Text == "" && lblThirdAppearance.Text == "")
            {
                AjaxFuncs.MsgBox(this.Page, "Please select media!");
                return;
            }
            if (lblFirstAppearance.Text != "" && ddlEstimatedhoursFirstAppearance.SelectedIndex == 0 && ddlEstimatedMinutesFirstAppearance.SelectedIndex == 0)
            {
                AjaxFuncs.MsgBox(this.Page, "Please select estimated hours for First Appearance!");
                return;
            }
            if (lblSecondAppearance.Text != "" && ddlEstimatedhoursSecondAppearance.SelectedIndex == 0 && ddlEstimatedMinutesSecondAppearance.SelectedIndex == 0)
            {
                AjaxFuncs.MsgBox(this.Page,
                                                      "Please select estimated hours for Second Appearance!");
                return;
            }
            if (lblThirdAppearance.Text != "" && ddlEstimatedhoursThirdAppearance.SelectedIndex == 0 && ddlEstimatedMinutesThirdAppearance.SelectedIndex == 0)
            {
                AjaxFuncs.MsgBox(this.Page,
                                                      "Please select estimated hours for Third Appearance!");
                return;
            }
            divError.Visible = false;
            divsuccess.Visible = false;
            try
            {
                DataTable dt = SPs.EmailAddressesForNewCommercial(0).GetDataSet().Tables[0];
                TblHistoricalDataForNewCommercial data = new TblHistoricalDataForNewCommercial();
                if (dt.Rows.Count > 0)
                {

                    string ddlHour = ddlHours.SelectedValue.ToString();
                    ddlHour = (ddlHour == "hr") ? "00" : ddlHour;

                    string ddlMinute = ddlMinutes.SelectedValue.ToString();
                    ddlMinute = (ddlMinute == "min") ? "00" : ddlMinute;
                    string ddlSecond = ddlSeconds.SelectedValue.ToString();
                    ddlSecond = (ddlSecond == "sec") ? "00" : ddlSecond;
                    sectorCode = lstSector.SelectedValue.ToString();
                    sectorCode = (sectorCode == "0") ? "ALL" : lstSector.SelectedItem.Text.ToString();
                    subsector = lstSubSector.SelectedValue.ToString();
                    subsector = (subsector == "0") ? "ALL" : lstSubSector.SelectedItem.Text.ToString();
                    advertiser = lstAdvertiser.SelectedValue.ToString();
                    advertiser = (advertiser == "0") ? "ALL" : lstAdvertiser.SelectedItem.Text.ToString();
                    
                    foreach (ListItem itm in lstMedia.Items)
                    {
                        if (itm.Selected)
                            mediaCodes += itm.Text + ",";
                    }

                    mediaCodes = mediaCodes.TrimEnd(',');
                    if (lstCategory.SelectedValue.ToString() == "Not Found")
                        categoryCode = "<b>Not Found</b> New category added :- " + txtCategory.Text.Trim();
                    else if (lstCategory.SelectedValue.ToString() == "0")
                        categoryCode = "ALL";
                    else
                        categoryCode = lstCategory.SelectedItem.Text.ToString();
                    string generateId = GenerateId();
                    string body = "<b>Form Code :- " + generateId + "<br></b>" +
                        "User Name :- " + Session["UserName"].ToString() + "<br>" +
                        "User Email Address :- " + Session["email"].ToString() + "<br>" +
                        "Product :- " + txtProduct.Text.Trim() + "<br>" +
    "Version :- " + txtVersion.Text.Trim() + "<br>" +
    "Departure Date :- " + string.Format("{0:MM/dd/yyyy}", RadDatePicker1.SelectedDate) + "<br>" +
    "Duration :- " + ddlHour + ":" + ddlMinute + ":" + ddlSecond + "<br>" +
    "Sector :- " + sectorCode + "<br>" +
    "Sub Sector :- " + subsector + "<br>" +
    "Category :- " + categoryCode + "<br>" +
    "Advertiser :- " + advertiser + "<br>" +
    "Agency :- " + txtAgency.Text.Trim() + "<br>" +
                        // "Media Type :-" + mediaCodes + "<br>" +
   "First Appearance :- " + lblFirstAppearance.Text.TrimEnd(',') + "<br>" +
   "Estimated hours for First Appearance :- " + ddlEstimatedhoursFirstAppearance.SelectedValue + ":" + ddlEstimatedMinutesFirstAppearance.SelectedValue + "<br>" +
   "Program Name for First Appearance :- " + txtProgramNameFirstAppearance.Text.Trim() + "<br>" +
    "Second Appearance :- " + lblSecondAppearance.Text.TrimEnd(',') + "<br>" +
    "Estimated hours for Second Appearance :- " + ddlEstimatedhoursSecondAppearance.SelectedValue + ":" + ddlEstimatedMinutesSecondAppearance.SelectedValue + "<br>" +
    "Program Name for Second Appearance :- " + txtProgramNameSecondAppearance.Text.Trim() + "<br>" +
    "Third Appearance :- " + lblThirdAppearance.Text.TrimEnd(',') + "<br>" +
     "Estimated hours for Third Appearance :- " + ddlEstimatedhoursThirdAppearance.SelectedValue + ":" + ddlEstimatedMinutesThirdAppearance.SelectedValue + "<br>" +
    "Program Name for Third Appearance :- " + txtProgramNameThirdAppearance.Text.Trim() + "<br>" +

   // "Estimated Hour :-" + estHour + ":" + estMinute + "<br>" +
    "Comments :- " + txtComments.Text.Trim();

                    if (hdnImageFileName.Value.Length > 0)
                        body += "<br><br><br> <a href='" + Utility.AppPath + "/downloadNewCommercialFile.aspx?filename=" + hdnImageFileName.Value.Replace('.', '_') + "'>Click here for download file</a>";
                    hdnImageFileName.Value = "";
                    data.UserID = Convert.ToInt32(Session["UserID"]);
                    data.CompanyCode = Convert.ToInt32(Session["CompanyCode"]);
                    data.UserName = Session["UserName"].ToString();
                    data.Product = txtProduct.Text.Trim();
                    data.Version = txtVersion.Text.Trim();
                    data.LaunchDay = string.Format("{0:yyyy-MM-dd}", RadDatePicker1.SelectedDate);
                    data.Duration = ddlHour + ":" + ddlMinute + ":" + ddlSecond;
                    data.Sector = sectorCode;
                    data.SubSector = subsector;
                    data.Category = categoryCode;
                    data.Advertiser = advertiser;
                    data.Agency = txtAgency.Text.Trim();
                    data.FirstAppearance = lblFirstAppearance.Text.TrimEnd(',');
                    data.EstimatedHours1 = ddlEstimatedhoursSecondAppearance.SelectedValue + ":" + ddlEstimatedMinutesSecondAppearance.SelectedValue;
                    data.ProgramName1 = txtProgramNameFirstAppearance.Text.Trim();
                    data.SecondAppearance = lblSecondAppearance.Text.TrimEnd(',');
                    data.EstimatedHours2 = ddlEstimatedhoursSecondAppearance.SelectedValue + ":" + ddlEstimatedMinutesSecondAppearance.SelectedValue;
                    data.ProgramName2 = txtProgramNameSecondAppearance.Text.Trim();
                    data.ThirdAppearance = lblThirdAppearance.Text.TrimEnd(',');
                    data.EstimatedHours3 = ddlEstimatedhoursThirdAppearance.SelectedValue + ":" + ddlEstimatedMinutesThirdAppearance.SelectedValue;
                    data.ProgramName3 = txtProgramNameThirdAppearance.Text.Trim();
                    data.Comments = txtComments.Text.Trim();
                    data.UploadCommercial = hdnImageFileName.Value.Replace('.', '_');
                    data.GenerateId = generateId;
                    data.Save();
                    SendMail(hdnEmails.Value.TrimEnd(','), body);
                    reset();
                    AjaxFuncs.MsgBox(this.Page,
                                         "The mail has been sent successfully.");


                }
                else
                {
                    AjaxFuncs.MsgBox(this.Page,
                                        "Email address is not specified. Please contact admin.");
                    return;
                }
            }
            catch (Exception ex)
            {
                divSuccessSend.Visible = false;
                divErrorSend.Visible = true;
                //StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }



        }
        protected void btnReset_click(object sender, ImageClickEventArgs e)
        {
            reset();

        }
        private void SendMail(String Users, string body)
        {

            String msg = body;
            String title = "New Comercial";
            String toAccount = Users;
            //String toAccount = "niteshguleria@nascenture.com";
            String MyHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            String MySMTPPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            String MySMTPSSL = ConfigurationManager.AppSettings["SMTPSSL"].ToString();

            String fromAddr = AdminEmail;   //Email Address of Sender

            MailMessage smtpMssg = new MailMessage();
            smtpMssg.From = new MailAddress(fromAddr);

            if (toAccount.Contains(","))
            {
                string[] tos = toAccount.Split(',');
                for (int i = 0; i < tos.Length; i++)
                {
                    if (tos[i] == "," || tos[i] == "")
                    {
                    }
                    else
                    {
                        smtpMssg.To.Add(new MailAddress(tos[i].Replace(",", "")));
                    }
                }
            }
            else
            {
                smtpMssg.To.Add(new MailAddress(toAccount));
            }

            smtpMssg.Subject = title;
            smtpMssg.Body = msg;
            smtpMssg.IsBodyHtml = true;

            //smtpMssg.Attachments.Add(new Attachment(memoryStream, "News.pdf"));

            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort));
            //smtpClient.Timeout = 2147483647;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (MySMTPSSL == "true")
            {
                smtpClient.EnableSsl = true;
            }

            try
            {
                smtpClient.Send(smtpMssg);

            }
            catch (Exception ex)
            {

                throw new Exception("Email not sent | Reason: [" + ex.Message + "]");

            }
        }
        public static int DateTimeToInt(DateTime theDate)
        {
            string month = theDate.Month.ToString();
            string Day = theDate.Day.ToString();
            month = (month.Length < 2) ? "0" + month : month;
            Day = (Day.Length < 2) ? "0" + Day : Day;
            int date = Convert.ToInt32(theDate.Year.ToString() + month.ToString() + Day.ToString());
            return date;
        }
        protected void imgBtnUpload_Click(object sender, ImageClickEventArgs e)
        {
            string filename = Path.GetFileName(FileUploadControl.FileName);
            if (FileUploadControl.HasFile)
            {
                FileUploadControl.SaveAs(Server.MapPath("~/NewCommercialByUsers/") + filename);
                hdnImageFileName.Value = filename;
                divsuccess.Visible = true;
                divError.Visible = false;
            }
            else
            {
                divError.Visible = true;
                divsuccess.Visible = false;
            }

        }
        public void reset()
        {
            txtCategory.Text = string.Empty;
            txtProduct.Text = string.Empty;
            // txtProgramName.Text = string.Empty;
            txtVersion.Text = string.Empty;
            lblFirstAppearance.Text = string.Empty;
            lblThirdAppearance.Text = string.Empty;
            lblSecondAppearance.Text = string.Empty;
            lnkbtnFirstAppearance.Visible = true;
            lnkbtnSecondAppearance.Visible = true;
            lnkbtnThirdAppearance.Visible = true;
            ddlEstimatedhoursFirstAppearance.Enabled = false;
            ddlEstimatedhoursSecondAppearance.Enabled = false;
            ddlEstimatedhoursThirdAppearance.Enabled = false;
            ddlEstimatedMinutesFirstAppearance.Enabled = false;
            ddlEstimatedMinutesSecondAppearance.Enabled = false;
            ddlEstimatedMinutesThirdAppearance.Enabled = false;
            txtProgramNameFirstAppearance.Enabled = false;
            txtProgramNameSecondAppearance.Enabled = false;
            txtProgramNameThirdAppearance.Enabled = false;
            txtProgramNameFirstAppearance.Text = string.Empty;
            txtProgramNameSecondAppearance.Text = string.Empty;
            txtProgramNameThirdAppearance.Text = string.Empty;
            RadDatePicker1.Clear();
            ddlBinds();
            txtComments.Text = string.Empty;


            FillMediaTypes();

            FillSectors();
            FillSubSectors();
            FillCategories();
            FillAdvertisers();
            FillMedia(1);
            hdnEmails.Value = string.Empty;
            hdnMediaAllCodeforEmails.Value = string.Empty;



        }
        protected void lnkbtnFirstAppearance_click(object sender, EventArgs e)
        {
            hdnMediaCodeType.Value = "1";
            ModalPopupExtender4.Show();

            FillMedia(1);
        }
        protected void lnkbtnSecondAppearance_click(object sender, EventArgs e)
        {
            hdnMediaCodeType.Value = "3";
            ModalPopupExtender4.Show();
            FillMedia(1);
        }
        protected void lnkbtnThirdAppearance_click(object sender, EventArgs e)
        {
            hdnMediaCodeType.Value = "5";
            ModalPopupExtender4.Show();
            FillMedia(1);
        }
        protected void btnSaveTV_Click(object sender, EventArgs e)
        {

            foreach (ListItem itm in lstMedia.Items)
            {
                if (itm.Selected)
                    mediaCodes += itm.Text + ",";
            }
            switch (hdnMediaCodeType.Value)
            {
                case "1":
                    lnkbtnFirstAppearance.Visible = false;
                    lblFirstAppearance.Text = mediaCodes.TrimEnd(',');
                    ddlEstimatedhoursFirstAppearance.Enabled = true;
                    ddlEstimatedMinutesFirstAppearance.Enabled = true;
                    txtProgramNameFirstAppearance.Enabled = true;

                    break;
                case "3":
                    lnkbtnSecondAppearance.Visible = false;
                    lblSecondAppearance.Text = mediaCodes.TrimEnd(',');
                    ddlEstimatedhoursSecondAppearance.Enabled = true;
                    ddlEstimatedMinutesSecondAppearance.Enabled = true;
                    txtProgramNameSecondAppearance.Enabled = true;

                    break;
                case "5":
                    lnkbtnThirdAppearance.Visible = false;
                    lblThirdAppearance.Text = mediaCodes.TrimEnd(',');
                    ddlEstimatedhoursThirdAppearance.Enabled = true;
                    ddlEstimatedMinutesThirdAppearance.Enabled = true;
                    txtProgramNameThirdAppearance.Enabled = true;
                    break;
            }
            if (!hdnMediaAllCodeforEmails.Value.Contains(lstMediaType.SelectedValue))
            {
                hdnEmails.Value += emailsTO(Utility.ToInt(lstMediaType.SelectedValue));
                hdnMediaAllCodeforEmails.Value += lstMediaType.SelectedValue;
            }

        }
        protected void btnCancelTV_click(object sender, EventArgs e)
        {
            ModalPopupExtender4.Hide();
            hdnMediaCodeType.Value = "";
        }
        private string emailsTO(int mediaType)
        {
            DataTable dt = SPs.EmailAddressesForNewCommercial(mediaType).GetDataSet().Tables[0];
            string emailTo = string.Empty;
            if (dt.Rows.Count > 0)
            {
                emailTo = dt.Rows[0]["EmailID1"].ToString() + ",";
                if (dt.Rows[0]["EmailID2"].ToString() != "")
                    emailTo += dt.Rows[0]["EmailID2"].ToString() + ",";
                if (dt.Rows[0]["EmailID3"].ToString() != "")
                    emailTo += dt.Rows[0]["EmailID3"].ToString() + ",";
                if (dt.Rows[0]["EmailID4"].ToString() != "")
                    emailTo += dt.Rows[0]["EmailID4"].ToString() + ",";
                if (dt.Rows[0]["EmailID5"].ToString() != "")
                    emailTo += dt.Rows[0]["EmailID5"].ToString() + ",";
            }
            return emailTo;
        }
    }
}